/*
 * Description: 数字单位输入框
 * Author: ty
 * Created on 2025-8-8 15:44
 */

<template>
    <el-input-number  class="yd-unit-number"
        v-number-input="{ precision: this.$attrs.precision, min: this.$attrs.min, max: this.$attrs.max }"
        v-model="val" 
        v-bind="$attrs"
        :controls="false"
        @blur="$emit('blur', $event)"
        @focus="$emit('focus', $event)"></el-input-number>
</template>
<script>
export default {
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        value: {
            type: [String, Number, undefined],
            default: undefined
        },
        unit: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            observer: null,
        };
    },
    computed: {
        val: {
            get() {
                if(this.value === '' || this.value === undefined || (typeof this.value == 'object' && this.value+'' === 'null')) {
                    return undefined
                }
                return this.value;
            },
            set(val) {
                this.$emit('change', val);
            }
        }
    },
    mounted() {
        this.observer = new IntersectionObserver((entries) => {
            entries.forEach(entrie => {
                // 是否进入在视口中
                if(entrie.isIntersecting) {
                    let oUnit = document.createElement('span');
                    oUnit.className = 'yd-number-unit';
                    oUnit.innerText = this.unit;
                    entrie.target.appendChild(oUnit);
                    // 移除对象观察
                    this.observer.unobserve(entrie.target);
                }
            })
        })
        this.$nextTick(() => {
            this.observer.observe(this.$el);
        });
    },
    beforeDestroy() {
        this.observer.disconnect();
    },
    methods: {
        
    }
};
</script>
<style scoped lang='scss'>
.yd-unit-number-box {
    position: relative;
    width: 100%;
    
}
.yd-unit-number {
    position: relative;
    width: 100%;
    ::v-deep .el-input__inner {
        text-align: left;
        padding-right: 24px;
    }
    ::v-deep .yd-number-unit {
        position: absolute;
        z-index: 1;
        right: 10px;
        top: 50%;
        margin-top: -10px;
        line-height: 20px;
        height: 20px;
        font-size: 14px;
    }
}
</style>